<template>
	<view class="container">

		<view class="tab-box1">
			<view class="status_bar"></view>
			<view class="head flex-row">
				<view class="title">通讯录</view>
				<view class="search-box">
					<!-- <u-search placeholder="请输入您想搜索的内容" :showAction="false" searchIconColor="#373737"
						placeholderColor="#bcbcbc"></u-search> -->
				</view>
				<view style="display: flex;">
				</view>
			</view>
			
			<view class="tab-box">
				<u-grid :border="false" @tap="handleclick">
					<u-grid-item v-for="(baseListItem,baseListIndex) in baseList" :key="baseListIndex">
						<!-- <u-icon :customStyle="{paddingTop:20+'rpx'}" :name="baseListItem.name" :size="22"></u-icon> -->
						<image :src="baseListItem.url" class="tab-icon"></image>
						<text class="grid-text">{{baseListItem.title}}</text>
					</u-grid-item>
				</u-grid>
				<u-toast ref="uToast" />
			</view>
		</view>
		<!--容器-->
		<view class="tab-box2">
			<!-- margin-bottom: 50px; -->
			<scroll-view :scroll-y="false" class="list"
				:style="`position: fixed;width: 100%;height: calc(100% - 200px);padding-bottom:0px;`">
				<u-index-list :index-list="validIndexList" :height="`100%`">
					<view v-for="(item, index) in validItemArr">

						<u-index-item>
							<!-- #ifdef APP -->
							<u-index-anchor :text="validIndexList[index]"></u-index-anchor>
							<!-- #endif -->
							<view class="list-cell" v-for="(cell, index) in item" @tap="toDetail(cell)"
								:id="'cell' + validIndexList[index]">

								<view v-if="cell.userAvatarFileName" class="name-img" style="position: relative;">
									<image
										:src="`http://chat.zwsmcn.com:8090/UserAvatarDownloader?action=ad&user_uid=${cell.user_uid}&user_local_cached_avatar=${cell.userAvatarFileName}&enforceDawnload=1`"
										class="name-img">
									</image>
									<view :class="(cell.online || JSON.parse(cell.online)) ? 'zaixian' : 'lixian'">
									</view>
								</view>

								<view class="name-img" v-else>
									{{cell.nickname[0]}}
									<view :class="(cell.online || JSON.parse(cell.online)) ? 'zaixian' : 'lixian'">
									</view>
								</view>

								<view style="margin-left: 50upx; font-weight: 300;">
									<view
										style="font-size: 28upx;display: flex;justify-content: start;align-items: center;">
										<view v-if="cell.ex10 == 1" style="color: #ba7953;">
											{{ cell.friendRemark === "" ? cell.nickname : cell.friendRemark }}
										</view>
										<view v-if="cell.ex10==0">
											{{ cell.friendRemark === "" ? cell.nickname : cell.friendRemark }}
										</view>

									</view>
									<!-- <view v-if="cell.liveStatus==1" style="font-size: 28upx;">在线</view> -->
									<view style="font-size: 12px;">
										{{(cell.online || JSON.parse(cell.online)) ? '在线' : $util.getTimediffer(cell.online_time) + '前在线'}}
									</view>
								</view>
							</view>
						</u-index-item>
					</view>

				</u-index-list>
			</scroll-view>
		</view>
		
	</view>
</template>

<script>
	import StringTool from "../../tools/StringTool";
	export default {
		components: {
			
		},
		data() {
			return {

				user: {},
				list: [{
						friendName: 'aaa',
					},
					{
						friendName: 'bbb',
					},
					{
						friendName: 'ccc',
					},
					{
						friendName: 'ddd',
					}
				],
				telephone: '',
				baseList: [{
						name: 'photo',
						title: '新的朋友',
						url: '../../static/image/group@3x.png'
					},
					{
						name: 'lock',
						title: '我的群组',
						url: '../../static/image/new-user@3x.png'
					},
					
				],
				indexList: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
					"T", "U", "V", "W", "X", "Y", "Z", "#"
				],
				itemArr: []
			}
		},
		computed: {
			validIndexList() {
				if (this.itemArr && this.itemArr.length > 0) {
					return this.indexList.filter((_, index) => this.itemArr[index] && this.itemArr[index].length > 0);
				}
				return []; // 如果 itemArr 不符合条件，返回空数组
			},
			// 返回非空的项目数组
			validItemArr() {
				// return [];
				return this.itemArr.filter(item => item && item.length > 0);
			}
		},
		onShow() {
			// #ifdef APP
			this.DB.isTable("friend" + uni.getStorageSync("user_uid")).then((res) => {
				// console.log(res);
				if (res) {
					this.DB.selectTableData("friend" + uni.getStorageSync("user_uid"))
						.then(res => {
							console.log("contact表数据-=-=-=-==-==-", res);

							let originalArray = res
							originalArray.map(item => {
								let firstChar = item.nickname.charAt(0).toUpperCase(); // 获取首字符
								if (/^[A-Z]$/.test(firstChar)) { // 检查是否为字母
									// 如果是字母，直接比较
								} else {
									firstChar = StringTool.getFirstLetter(item.nickname).charAt(0)
										.toUpperCase();
								}
								// console.log(item.nickname);
								let firstChar_index = firstChar.charCodeAt(0) - 'A'.charCodeAt(0)

								item.online = JSON.parse(item.online)

								if (firstChar_index >= 0) {
									let index = this.itemArr[firstChar_index].findIndex(f_itme =>
										f_itme
										.user_uid == item
										.user_uid)
									if (index >= 0) {
										this.itemArr[firstChar_index][index] = item;
									} else {
										this.itemArr[firstChar_index].push(item)
									}
								} else {
									let firstChar_index = 26
									let index = this.itemArr[firstChar_index].findIndex(f_itme =>
										f_itme
										.user_uid == item
										.user_uid)
									if (index >= 0) {
										this.itemArr[firstChar_index][index] = item;
									} else {
										this.itemArr[firstChar_index].push(item)
									}
								}
							})

							console.log(this.itemArr);
							this.$forceUpdate();

							// this.indexList.forEach((char, index) => {
							// 	// this.itemArr;
							// 	this.itemArr.push(originalArray.filter(f => StringTool.getFirstLetter(f	.nickname).charAt(0).toUpperCase() === char))

							// })

							// console.log(this.itemArr);


						})
						.catch(error => {
							console.log("查询失败", error);
							this.getList()

						});
				} else {
					let sql =
						'id INTEGER PRIMARY KEY AUTOINCREMENT, nickname text, userAvatarFileName text, user_mail text, user_sex text, user_uid text, online text,whatsUp text, online_time text,ex10 text,friendRemark text';
					// 创建表 DB.createTable(表名, 表的列)


					this.DB.createTable("friend" + uni.getStorageSync("user_uid"), sql)
						.then(res => {
							console.log("创建chat表成功", res);
						})
						.catch(error => {
							console.log("创建表失败", error);
						});
				}
			})

			// #endif


			this.getfriendlist()
		},
		onLoad() {

			this.initializeArray();
			let open = this.DB.isOpen();
			if (!open) {
				this.DB.openSqlite()
					.then(res => {
						console.log("数据库已打开");
					})
					.catch(error => {
						console.log("数据库开启失败");
					});
			}
			// this.itemArr = [];
			// #ifdef MP-WEIXIN
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.posRight = (menuButtonInfo.width + 20) + 'px'
			// #endif
			//// this.getList()


		},
		methods: {
			initializeArray() {
				let array = [];
				for (let i = 0; i < 27; i++) {
					array.push(new Array().fill(0)); // 这里用0填充，你可以根据需要填充其他值或对象
				}
				this.itemArr = array;
			},

			getfriendlist() {

				// const newDataObj = {
				// 	"user_uid": uni.getStorageSync('user_uid'),
				// };
				// const newDataJsonStr = JSON.stringify(newDataObj)
				const requestData = {
					"processorId": '1008',
					"jobDispatchId": '2',
					"actionId": '7',
					"newData": uni.getStorageSync('user_uid')
				};
				const requestDataJsonStr = JSON.stringify(requestData);
				uni.request({
					url: 'http://chat.zwsmcn.com:8090/rest_post',
					header: {
						'content-type': 'application/json'
					},
					data: requestDataJsonStr,
					method: 'POST',
					success: res => {
						console.log(JSON.parse(res.data.returnValue))
						uni.hideLoading()

						// #ifdef APP
						this.DB.deleteTableData("friend" + uni.getStorageSync("user_uid"))
							.then(res => {
								console.log("删除表数据成功", res);
							})
							.catch(error => {
								console.log("删除失败", error);
							});
						// #endif


						let originalArray_res = JSON.parse(res.data.returnValue)
						let originalArray = []
						let nicknamehashMap = new Map();;
						let avatarhashMap = new Map();

						originalArray_res.map(item => {



							item.online_time = item.ex13.length > 0 ? (item.ex13.length > 10 ? item
								.ex13 : item.ex13 + '000') : Math.floor(uni.MBUtils
								.getCurrentUTCTimestamp());


							let firstChar = item.nickname.charAt(0).toUpperCase(); // 获取首字符
							if (/^[A-Z]$/.test(firstChar)) { // 检查是否为字母
								// 如果是字母，直接比较
							} else {
								firstChar = StringTool.getFirstLetter(item.nickname).charAt(0)
									.toUpperCase();
							}
							// console.log(item.nickname);
							let firstChar_index = firstChar.charCodeAt(0) - 'A'.charCodeAt(0)


							if (firstChar_index >= 0) {
								let index = this.itemArr[firstChar_index].findIndex(f_itme => f_itme
									.user_uid == item
									.user_uid)
								if (index >= 0) {
									this.itemArr[firstChar_index][index] = item;
								} else {
									this.itemArr[firstChar_index].push(item)
								}
							} else {
								firstChar_index = 26
								let index = this.itemArr[firstChar_index].findIndex(f_itme => f_itme
									.user_uid == item
									.user_uid)
								if (index >= 0) {
									this.itemArr[firstChar_index][index] = item;
								} else {
									this.itemArr[firstChar_index].push(item)
								}
							}

							originalArray.push(item);
							nicknamehashMap.set(item.user_uid, item.nickname);


							avatarhashMap.set(item.user_uid, item.userAvatarFileName);
							uni.setStorageSync('avatarhashMap', JSON.stringify(Array.from(
								avatarhashMap)))
							uni.setStorageSync('nicknamehashMap', JSON.stringify(Array.from(
								nicknamehashMap)))
							// console.log(avatarhashMap.get(item.user_uid));
							let online_time = item
								.online_time; // item.status_time ??Math.floor(uni.MBUtils.getCurrentUTCTimestamp())

							let sql1 =
								`'${item.nickname}', '${item.userAvatarFileName}', '${item.user_mail}', '${item.user_sex}', '${item.user_uid}', '${String(item.online)}', '${item.whatsUp}','${online_time}','${item.ex10}','${item.friendRemark}'`;

							let condition =
								'nickname , userAvatarFileName , user_mail , user_sex , user_uid , online ,whatsUp,online_time,ex10,friendRemark ';
							// 新增 DB.insertTableData(表名, 对应表头列的数据)
							// #ifdef APP
							// console.log(sql1);
							this.DB.insertTableData("friend" + uni.getStorageSync("user_uid"), sql1,
									condition)
								.then(res => {
									console.log("新增数据成功");
								})
								.catch(error => {
									console.log("失败", error);
								});
							// #endif	
						})
						// console.log(uni.getStorageSync('nicknamehashMap'))

						// console.log(originalArray)

						// this.indexList.forEach((char, index) => {
						// 	this.itemArr.push(originalArray.filter(f => StringTool.getFirstLetter(f
						// 		.nickname).charAt(0).toUpperCase() === char))

						// })

						// return;

						// this.itemArr = [];
						this.indexList.forEach((char, index) => {
							// this.itemArr.push(originalArray.filter(f => StringTool.getFirstLetter(f
							// 	.nickname).charAt(0).toUpperCase() === char))
							// this.itemArr = this.indexList.map(char =>
							// 	originalArray.filter(f => {
							// 		const firstChar = f.nickname.charAt(0)
							// 	.toUpperCase(); // 获取首字符
							// 		if (/^[A-Z]$/.test(firstChar)) { // 检查是否为字母
							// 			return firstChar === char; // 如果是字母，直接比较
							// 		}
							// 		// 如果不是字母，使用 StringTool 转换后再比较
							// 		return StringTool.getFirstLetter(f.nickname).charAt(0)
							// 			.toUpperCase() === char;
							// 	})
							// );
						})

						this.$forceUpdate();
						console.log(this.itemArr)
					},
					fail: res => {
						console.log(res);
					}
				});
			},
			// 取消添加
			cancelAdd() {
				this.$refs.addFriend.close()
				this.telephone = ''
			},
			// 添加好友
			addFriend() {
				this.$refs.addFriend.open()
			},
			addFriendAction() {
				if (!this.$validate.isPhone(this.telephone)) {
					return this.$util.toast('手机号格式错误')
				}

				this.$util.loading('添加中')
				uni.request({
					method: 'POST',
					url: this.$api.addFriend,
					data: {
						userId: uni.getStorageSync('userId'),
						telephone: this.telephone
					},
					header: this.$util.getHeader(),
					success: res => {
						uni.hideLoading()
						if (res.data.code) {
							return this.$util.toast(res.data.msg)
						}
						this.$refs.addFriend.close()
						this.telephone = ''
						// this.getList()
					},
					fail: err => {
						uni.hideLoading()
						this.$util.toast('添加失败')
					}
				})
			},
			// 详情
			toDetail(item) {
				console.log(item.user_uid)
				let user_uid = item.user_uid

				uni.navigateTo({
					url: '/pages/contacts/information?user_uid=' + user_uid
				});
			},
			// 获取好友列表
			// getList() {
			// 	this.$util.loading('加载中')
			// 	uni.request({
			// 		method: 'POST',
			// 		url: this.$api.getFriends,
			// 		data: {
			// 			userId: uni.getStorageSync('userId')
			// 		},
			// 		header: this.$util.getHeader(),
			// 		success: res => {
			// 			uni.hideLoading()
			// 			this.list = res.data.data
			// 		},
			// 		fail: err => {
			// 			uni.hideLoading()
			// 			this.$util.toast('获取失败')
			// 		}
			// 	})
			// },
			handleclick(name) {
				//this.$refs.uToast.success(`点击了第${name}个`)

				if (name == 0) {
					this.toPage('/pages/contacts/newFreends')
				} else if (name == 1) {
					this.toPage('/pages/contacts/myGroup')
				}
			},
			
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-index-list__letter {
		// margin-top: 120px !important;
	}

	.container {
		height: calc(100vh - 60px) !important;
	}

	// .container {
	// 	width: 100%;
	// 	height: 100%;
	// }

	.head {

		// margin-top: 30upx;
		.title {
			margin-top: 10upx;
		}
	}

	.u-index-anchor {
		height: 16px !important;
	}

	.tab-box {
		padding-top: 40upx;
		background-color: #FFF;

		image {
			width: 90upx;
			height: 90upx;
			// background-color: #000;
			border-radius: 12upx;
			padding: 16upx;
			opacity: 0.7;
		}
	}

	.tab-box1 {
		// position: fixed;
		// top: 0;
		// left: 0;
		width: 100%;
		// background-color: red;
		z-index: 90999;
	}

	.tab-box2 {
		position: fixed;
		top: 200px;
		left: 0;
		width: 92%;
		margin: 0 auto;
	}

	.tab-icon {
		width: 70upx;
		height: 70upx;
		border-radius: 10upx;
	}

	.grid-text {
		font-size: 14px;
		color: #909399;
		padding: 10rpx 0 20rpx 0rpx;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}

	.add-friend {
		width: 600upx;
		height: 460upx;
		padding: 0 40upx;
		border-radius: 10upx;
		background-color: #FFF;
		position: relative;

		.close {
			position: absolute;
			right: 20upx;
			top: 20upx;
		}

		.title {
			height: 120upx;
			font-size: 30upx;
			text-align: center;
			line-height: 120upx;
		}

		.input {
			height: 80upx;
			padding: 0 30upx;
			border-radius: 10upx;
			margin: 40upx 0 80upx;
			border: 2upx solid #ddd;
		}

		.btn {
			color: #FFF;
			height: 80upx;
			line-height: 80upx;
			text-align: center;
			border-radius: 10upx;
			background-color: #2CA246;

			&.disabled,
			&:active {
				opacity: 0.8;
			}
		}
	}

	.list {
		height: calc(100vh - 400upx);

		.item {
			width: 100vw;
			padding: 20upx 30upx 0;

			.cover {
				width: 80upx;
				height: 80upx;
				border-radius: 10upx;
				box-sizing: border-box;
				border: 2upx solid #f9f9f9;
				position: relative;

				.icon {
					width: 100%;
					height: 100%;
					border-radius: 10upx;
				}
			}

			.title {
				height: 100%;
				box-sizing: border-box;
				width: calc(100vw - 110upx - 60upx);
				position: relative;

				&::after {
					content: '';
					width: 100%;
					height: 2upx;
					background-color: #F6F6F6;
					position: absolute;
					left: 0;
					bottom: -34upx;
				}

				.main {
					margin: 6upx 0;

					.text {
						color: #333;
						font-size: 32upx;
						font-weight: 600;
					}

					.time {
						color: #666;
						font-size: 24upx;
					}
				}
			}
		}
	}

	.search-box {
		width: 60%;
		background-color: #fff;
		margin-top: 20upx;
		color: #2e2e2e;

	}

	.list-cell {
		display: flex;
		box-sizing: border-box;
		width: 100%;
		padding: 6px 24rpx;
		overflow: hidden;
		color: #323233;
		font-size: 14px;
		line-height: 24px;
		background-color: #fff;

		image {
			width: 100upx;
			height: 100upx;
			// border-radius: 50%;
		}
	}

	::v-deep .u-index-anchor {
		background-color: #fff !important;
		border: none;
	}

	.lixian {
		width: 20px;
		height: 20px;
		border-radius: 50%;
		// background-color: aquamarine;
		background-color: #909399;
		border: 2px solid #ffffff;
		position: absolute;
		right: -0px;
		bottom: 0px;
	}

	.zaixian {
		width: 20px;
		height: 20px;
		border-radius: 50%;
		background-color: #2CA246;
		border: 2px solid #ffffff;
		position: absolute;
		right: -0px;
		bottom: 0px;
	}

	.u-index-anchor {
		position: sticky;
		/* 使字母固定 */
		top: 0;
		z-index: 10;
		/* 设置为较高的值 */
	}

	.u-index-item {
		position: relative;
		z-index: 0;
		/* 保证内容层级较低 */
	}

	.name-img {
		position: relative;
		width: 100upx;
		height: 100upx;
		border-radius: 10px;
		background: #d54827;
		font-size: 36upx;
		text-align: center;
		line-height: 90upx;
		color: #fff;
		// margin-left: 10upx;
		// margin-top: -10upx;
	}

	.face {
		width: 80upx;
		height: 80upx;
		border-radius: 10px;
	}

	.dirlog-box {
		width: 40%;
		background: #fff;
		border-radius: 20upx;
		padding: 10upx 30upx;
		box-shadow: 0 0 40upx #000; // 左
		box-shadow: 0 0 40upx #000; // 右
		color: #2e2e2e;
		font-weight: 300;
		position: absolute;
		right: 3%;
		top: 11%;
		z-index: 1;

		.dirlog-box1 {
			display: flex;
			padding: 30upx 10upx;

			image {
				width: 60upx;
				height: 60upx;
			}

			view {
				margin-left: 20upx;
			}
		}
	}
</style>